<?php

use Lcobucci\JWT\Validation\RequiredConstraintsViolated;

function uploadImg($file, $path)
{
   $allow_ext = ['png','jpg','jpeg'];
   if($file->isValid()){
      $ext = $file->getClientOriginalExtension();
      if(!in_array($ext,$allow_ext)){
          return response()->json(['status'=>201,'msg'=>'上传图片格式不正确']);
      }
      $fileName = date("YmdHis").rand(1,1000).".".$ext;
      $file->move($path,$fileName);
      return response()->json(['status'=>200,'url'=>"/{$path}/{$fileName}"]);
   }
}

//生成签名数据
function createSign($params)
{
    unset($params['sign']);
    $params['key'] = env('API_KEY');
    ksort($params);
    $queryStr = "";
    foreach ($params as $key=>$item)
    {
        $queryStr .="$key=$item&";
    }
    $queryStr = rtrim($queryStr,"&");
    return md5($queryStr);
}

//生成token配置
function tokenConfig()
{
    $configuration = \Lcobucci\JWT\Configuration::forSymmetricSigner(
        new \Lcobucci\JWT\Signer\Hmac\Sha256(),
        // replace the value below with a key of your own!
        \Lcobucci\JWT\Signer\Key\InMemory::plainText(env('APP_KEY'))
    );
    return $configuration;
}
//生成token
function createToken($uid)
{
    $now = new \DateTimeImmutable();
    $config = tokenConfig();
    $token = $config->builder()
        ->issuedAt($now)
        ->expiresAt($now->modify('+1 hour'))
        ->withClaim('uid', $uid)
        ->getToken($config->signer(), $config->signingKey());
    return $token->toString();
}

//解析token
function parseToken($jwt)
{
    $config = tokenConfig();
    $token = $config->parser()->parse($jwt);
    if (! $config->validator($token, ...$config->validationConstraints())) {
        throw new \InvalidArgumentException('Invalid token provided');
    }
    return $token->claims()->get('uid');
}

if(!function_exists("tokenValiator"))
{
    //验证token有效性
    function tokenValiator($token)
    {
      $parser = new \Lcobucci\JWT\Token\Parser(new \Lcobucci\JWT\Encoding\JoseEncoder());
      $token = $parser->parse($token);
      $validator = new \Lcobucci\JWT\Validation\Validator();
      try{
      }catch (RequiredConstraintsViolated $e){
          var_dump($e->violations());
      }
        dd('11');
    }
}

if(!function_exists('generateSign')){
    function generateSign($params) {
        ksort($params);
        $string = '';
        foreach ($params as $key => $value) {
            if ($key != 'sign' && $value != '') {
                $string .= "{$key}={$value}&";
            }
        }
        $string .= "key=" . env("WX_APP_SECRET");
        return strtoupper(md5($string));
    }
}
